<script setup lang="ts">
import { ref, onMounted, onBeforeMount } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import { getDictByCode } from "@/api/dictApi";
import host from "@/utils/http/env";
import { saveProduct, updateProductById } from "@/api/productApi";
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();
//产品图片
const imageUrl = ref("");
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  if (response.code === 200) {
    formData.value.coverImage = host + response.data;
    ElMessage({
      type: "success",
      message: response.msg
    });
  }
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("头像图片必须是 JPG 格式!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("文件大小超过10MB");
    return false;
  }
  return true;
};

//下拉列表
onMounted(() => {
  dict();
});
onBeforeMount(() => {
  formData.value = route.query;
});

async function dict() {
  //筛网材质
  let res1 = await getDictByCode(13);
  materialOptions.value = res1.data.subDict;
  //分类
  let res2 = await getDictByCode(15);
  categoryOptions.value = res2.data.subDict;
  //型号
  let res3 = await getDictByCode(16);
  modelOptions.value = res3.data.subDict;
  //品牌
  let res4 = await getDictByCode(14);
  brandOptions.value = res4.data.subDict;
}
const materialOptions = ref();
const categoryOptions = ref();
const modelOptions = ref();
const brandOptions = ref();
const formData = ref({
  id: "",
  productType: "1",
  productUnit: "",
  productNumber: "",
  productName: "",
  coverImage: "",
  model: "",
  categoryCode: "",
  categoryName: "",
  specificationBarCode: "",
  specificationCode: "",
  brand: "",
  material: "",
  singleWeight: "",
  outerSize: "",
  productDrawingNumber: "",
  factoryDrawingNumber: "",
  originalDrawingNumber: "",
  stock: "",
  price: "",
  sort: "",
  lowStockWarningValue: "",
  highStockWarningValue: "",
  brandInfo: "",
  productDetails: "",
  status: "",
  createBy: ""
});
function save() {
  if (!formRef.value) return;
  formRef.value.validate(async valid => {
    if (valid) {
      let res = await saveProduct(formData.value);
      if (res.code == 200) {
        ElMessage({
          message: "添加产品成功",
          type: "success"
        });
        reset();
        router.push({ path: "/adminProduct/productManage" });
      }
    }
  });
}
//重置参数
function reset() {
  formData.value = {
    id: "",
    productType: "1",
    productUnit: "",
    productNumber: "",
    productName: "",
    coverImage: "",
    model: "",
    categoryCode: "",
    categoryName: "",
    specificationBarCode: "",
    specificationCode: "",
    brand: "",
    material: "",
    singleWeight: "",
    outerSize: "",
    productDrawingNumber: "",
    factoryDrawingNumber: "",
    originalDrawingNumber: "",
    stock: "",
    price: "",
    sort: "",
    lowStockWarningValue: "",
    highStockWarningValue: "",
    brandInfo: "",
    productDetails: "",
    status: "",
    createBy: ""
  };
}
//取消
function Cancel() {
  reset();
  router.push({ path: "/adminProduct/productManage" });
  formRef.value.resetFields();
}
//修改产品
function update() {
  if (!formRef.value) return;
  formRef.value.validate(async valid => {
    if (valid) {
      let res = await updateProductById(formData.value);
      reset();
      router.push({ path: "/adminProduct/productManage" });
    }
  });
}
//表单校验对象
const formRef = ref();
</script>

<template>
  <div>
    <div>
      <!--添加商品表单 -->
      <el-card style="max-width: 1000px; margin: 0 auto">
        <template #header>
          <div class="card-header">
            <span>基础信息</span>
          </div>
        </template>

        <el-form
          ref="formRef"
          :model="formData"
          :inline="true"
          label-position="left"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="产品类型:"
                prop="productType"
                :required="true"
              >
                <el-radio-group v-model="formData.productType">
                  <el-radio value="1">反击破产品</el-radio>
                  <el-radio value="2">鄂破产品</el-radio>
                  <el-radio value="3">圆锥类产品</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="产品单位:"
                prop="productUnit"
                :required="true"
              >
                <el-input
                  v-model="formData.productUnit"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="产品编号:"
                prop="productNumber"
                :required="true"
              >
                <el-input
                  v-model="formData.productNumber"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                v-if="route.query.id"
                label="产品名称:"
                prop="productName"
              >
                <el-input
                  v-model="formData.productName"
                  placeholder="请输入"
                  disabled
                  clearable
                />
              </el-form-item>
              <el-form-item
                v-else
                label="产品名称:"
                prop="productName"
                :required="true"
              >
                <el-input
                  v-model="formData.productName"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="封面图:" prop="coverImage" :required="true">
                <el-upload
                  list-type="picture-card"
                  class="avatar-uploader"
                  :action="host + '/' + 'upload'"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img
                    v-if="formData.coverImage"
                    :src="formData.coverImage"
                    class="avatar"
                  />
                  <el-icon v-else class="avatar-uploader-icon"
                    ><Plus
                  /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="轮播图:" prop="productName">
                <el-upload
                  list-type="picture-card"
                  class="avatar-uploader"
                  :action="host + '/' + 'upload'"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"
                    ><Plus
                  /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="产品分类:"
                prop="categoryName"
                :required="true"
              >
                <el-select
                  v-model="formData.categoryName"
                  placeholder="下拉选择二级分类"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in categoryOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="型号:" prop="model" :required="true">
                <el-select
                  v-model="formData.model"
                  placeholder="下拉选择已创建的型号"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in modelOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="规格条码:"
                prop="specificationBarCode"
                :required="true"
              >
                <el-input
                  v-model="formData.specificationBarCode"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="规格编码:"
                prop="specificationCode"
                :required="true"
              >
                <el-input
                  v-model="formData.specificationCode"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="品牌:" prop="brand" :required="true">
                <el-select
                  v-model="formData.brand"
                  placeholder="下拉选择"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in brandOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="材质:" prop="material" :required="true">
                <el-select
                  v-model="formData.material"
                  placeholder="下拉选择已创建的材质"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in materialOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="单重:" prop="singleWeight" :required="true">
                <el-input
                  v-model="formData.singleWeight"
                  placeholder="请输入(kg)"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="外形尺寸:" prop="outerSize" :required="true">
                <el-input
                  v-model="formData.outerSize"
                  placeholder="请输入(毫米)"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="产品图号:"
                prop="productDrawingNumber"
                :required="true"
              >
                <el-input
                  v-model="formData.productDrawingNumber"
                  placeholder="请输入 反击破产品非必填，其他为必填"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="工厂图号:"
                prop="factoryDrawingNumber"
                :required="true"
              >
                <el-input
                  v-model="formData.factoryDrawingNumber"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="原装图号:"
                prop="originalDrawingNumber"
                :required="true"
              >
                <el-input
                  v-model="formData.originalDrawingNumber"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库存:" prop="stock" :required="true">
                <el-input
                  v-model="formData.stock"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="价格:" prop="price" :required="true">
                <el-input
                  v-model="formData.price"
                  placeholder="请输入($)"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序:" prop="sort" :required="true">
                <el-input
                  v-model="formData.sort"
                  placeholder="数字越大越靠前"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="低库存预警值:"
                prop="lowStockWarningValue"
                :required="true"
              >
                <el-input
                  v-model="formData.lowStockWarningValue"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="高库存预警值:"
                prop="highStockWarningValue"
                :required="true"
              >
                <el-input
                  v-model="formData.highStockWarningValue"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="品牌资料:" prop="brandInfo">
                <el-input
                  v-model="formData.brandInfo"
                  style="width: 240px"
                  :rows="2"
                  type="textarea"
                  placeholder="富文本"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="产品详情:" prop="productDetails">
                <el-input
                  v-model="formData.productDetails"
                  style="width: 240px"
                  :rows="2"
                  type="textarea"
                  placeholder="富文本"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer
          ><el-button
            v-if="route.query.id"
            type="primary"
            style="width: 40%; margin-left: 50px"
            @click="update"
            >修改产品</el-button
          >
          <el-button
            v-else
            type="primary"
            style="width: 40%; margin-left: 50px"
            @click="save"
            >添加产品</el-button
          >
          <el-button type="primary" style="width: 40%" @click="Cancel"
            >取消</el-button
          ></template
        >
      </el-card>
    </div>
  </div>
</template>

<style lang="scss" scoped>
::v-deep.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

::v-deep.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

::v-deep.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 148px;
  height: 148px;
  display: block;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
</style>
